package com.cblz.bd.server.core.configure;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.cblz.bd.common.core.constant.BdAdminConstant;
import com.cblz.bd.server.core.annotation.AdminApiController;
import com.cblz.bd.server.core.annotation.UserApiController;
import com.cblz.bd.server.core.entity.properties.AuthApiProperties;
import com.cblz.bd.server.core.entity.properties.SecurityProperties;
import com.cblz.bd.server.core.interceptor.BaSecurityDataRecyInterceptor;
import com.cblz.bd.server.utils.StpUserUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * {@code @Name:} SaTokenConfigure
 * {@code @Description: } SaToken路由拦截配置
 * {@code @Author:} by yanjieping
 * {@code @CreateDate:} 2022/11/9 - 周三
 */
@Configuration
@EnableConfigurationProperties(SecurityProperties.class)
@RequiredArgsConstructor
public class SaTokenConfigure implements WebMvcConfigurer {

    private final SecurityProperties securityProperties;
    private final AuthApiProperties authApiProperties;
    private final BaSecurityDataRecyInterceptor baSecurityDataRecyInterceptor;

    /**
     * 注册拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 管理端免认证地址
        String[] adminAnonUrl = securityProperties.getAdminAnonUrl().split(BdAdminConstant.SYSTEM_COMMA.getVal());
        // 用户端免认证地址
        String[] userAnonUrl = securityProperties.getUserAnonUrl().split(BdAdminConstant.SYSTEM_COMMA.getVal());

        registry.addInterceptor(new SaInterceptor(handle -> {
            SaRouter.match(authApiProperties.getAdmin() + "/**").notMatch(adminAnonUrl).check(r -> StpUtil.checkLogin());

            SaRouter.match(authApiProperties.getUser() + "/**").notMatch(userAnonUrl).check(r -> StpUserUtil.checkLogin());
        }));

        registry.addInterceptor(baSecurityDataRecyInterceptor);
    }

    /**
     * 加入路径前缀
     *
     * @param configurer
     * @see PathMatchConfigurer
     * @since 4.0.3
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer
                .addPathPrefix(authApiProperties.getAdmin(), aClass -> aClass.isAnnotationPresent(AdminApiController.class))
                .addPathPrefix(authApiProperties.getUser(), aClass -> aClass.isAnnotationPresent(UserApiController.class));
    }
}
